import { nonEmpty } from '@/utils/non-empty';
import { EventNameMap, ErrorNameMap } from '@/constants';
import { ApiTrackReporter, CustomReporter, ReportContent, EventName, ErrorName } from '../types';
import { transform } from '@/utils/format-report-info';

interface ReporterOptions {
  biz_id?: string;
  env: string;
  options?: CustomReporter;
}
export class Reporter implements ApiTrackReporter {
  private env: {
    biz_id?: string;
    env: string;
  };

  baseInfo: Record<string, string>;
  private customReport?: CustomReporter;
  constructor({ biz_id, env, options }: ReporterOptions) {
    this.env = { biz_id, env };
    this.customReport = options;
    this.baseInfo = {};
  }

  setBaseInfo(baseInfo: Record<string, unknown>) {
    this.baseInfo = transform(nonEmpty(baseInfo));
  }

  sendLog(eventName: EventName | string, extra?: ReportContent<unknown>) {
    const reportName: string = typeof eventName === 'string' ? eventName : EventNameMap[eventName];
    const { categories, metrics } = extra || {};
    const reportInfo = nonEmpty({
      categories: transform(nonEmpty({ ...this.env, ...this.baseInfo, ...categories })),
      metrics,
    });
    this.customReport?.sendLog(reportName, reportInfo);
  }

  reportError(errorName: ErrorName, extra: Record<string, string>) {
    const reportName: string = ErrorNameMap[errorName];
    this.customReport?.reportError(reportName, { ...this.env, ...this.baseInfo, ...extra });
  }
}
